#!/bin/sh
DMS_NAMES[0]="Aria"
DMS_CMDS[0]='aria'
DMS_NAMES[1]="Downloader 4 X"
DMS_CMDS[1]='nt'

DMS_COUNT=${#DMS_CMDS[*]}

check() {
  echo -n "${DMS_NAMES[$j]}|"
  path=$(which "${DMS_CMDS[$j]}" 2>/dev/null) && echo "OK" || echo "BAD"
}

checkAll() {
 j=$DMS_COUNT; while (( j-- > 0 )); do
        check ${DMS_CMDS[$j]} "${DMS_NAMES[$j]}"
 done
}

launch_nt() {
  nt "$1" &
}

launch_aria() {
  aria -r "$referrer" $optSaveDir -g "$1" &
}

launch() {
  j=$DMS_COUNT; while (( j-- >0 )); do
        if [ "${DMS_NAMES[$j]}" == "$dmsName" ] ; then
          dmsCmd="${DMS_CMDS[$j]}"
          DMS_ID=$j
          j=0
        fi
  done
  optSaveDir=""
  case "$dmsCmd" in
    "nt" | "aria" )
      if [ "$saveDir" ]; then
        if [ "$dmsCmd" == "nt" ]; then
          nt -d "$saveDir" &
          sleep 1
        else
          optSaveDir=${saveDir:+-d"$saveDir"}
        fi
      fi
      j=0; while (( j<linksCount )); do
        "launch_$dmsCmd" "${urls[$j]}" "${info[$j]}" "${cookies[$j]}" "${postData[$j]}"
        echo "launched $dmsCmd" "url: ${urls[$j]}" "info: ${info[$j]}" "cookie: ${cookies[$j]}" "postData: ${postData[$j]}"
      (( j++ )); done
      if [ "$dmsCmd" == "aria" -a $linksCount -gt 0 ]; then
        sleep 3
        aria -s &
      fi
      ;;
     *) echo >2 "Unknown Download Manager $dmsName"
        ;;
   esac
}

if [ "$1" == "-o" ]; then
  echo "$(checkAll)" > "$2"
else
 
  ph() {
    ph="${line%%;*}" 
    line="${line#*;}"
  }
  
  parseFile() { 
    export linesIdx=0 linksIdx=0 linksCount=0 
    while read line; do
      case $linesIdx in
        0) ph && linksCount=$ph
           ph && dmsName=$ph
           ph && optType=$ph
           ph && saveDir=$ph
           ;;
        1) referrer="$line" ;;
        *) echo "linesIdx $linesIdx linksIdx $linksIdx linksCount $linksCount"
           if [ $linksIdx -lt $linksCount ]; then
            case $(( linesIdx % 4 )) in
              2) urls[$linksIdx]="$line" ;;
              3) info[$linksIdx]="$line" ;;
              0) cookies[$linskIdx]="$line" ;;
              1) postData[$linksIdx]="$line"
                 linksIdx=$(( linksIdx+1 )) 
                 ;;
            esac
           fi
           ;;
       esac
      linesIdx=$(( linesIdx+1 ))
    done
    echo "linesIdx $linesIdx linksIdx $linksIdx linksCount $linksCount"
    launch
  }
  
  cat "$1" | parseFile
  
fi


